/**
 * author:wos
 * time:2024-1-4
 * title:用户登陆
 */

const getUserIp = require('../../../utils/getUserIp'),
    md5 = require('md5'),
    jwt = require('jsonwebtoken'),
    {isTimestampExpired, getTimestampAfterSeconds} = require('../../../utils/timestamp'),
    {removeSpacesAndLower} = require('../../../utils/stringFormat'),
    redis = require('../../../modules/redis')

async function login(ctx, next) {
    const post = ctx.request.body
    if (!post.username || !post.password || !post.code || !post.uuid) {
        global.response(ctx, {
            "status": 200,
            "code": 500,
            "data": {},
            "msg": '参数错误'
        })
        addLoginLog(ctx, false, post.username,'参数错误')
        return
    }


    const uuid = jwt.verify(post.uuid, global.config.secret)

    //判断uuid是否有效
    if (typeof uuid !== 'object') {
        global.response(ctx, {
            "status": 200,
            "code": 500,
            "data": {},
            "msg": 'UUID错误'
        })
        addLoginLog(ctx, false, post.username,'UUID错误')
        return
    }
    //判断验证码是否过期
    if (isTimestampExpired(uuid.exp)) {
        global.response(ctx, {
            "status": 200,
            "code": 500,
            "data": {},
            "msg": '验证码过期'
        })
        addLoginLog(ctx, false, post.username,'验证码过期')
        return
    }
    //判断验证码是否匹配
    if (removeSpacesAndLower(uuid.data) !== removeSpacesAndLower(post.code)) {
        global.response(ctx, {
            "status": 200,
            "code": 500,
            "data": {},
            "msg": '验证码错误'
        })
        addLoginLog(ctx, false, post.username,'验证码错误')
        return
    }
    let sql = `select * from sys_user where username='${post.username}' and password='${md5(post.password)}'`
    // @ts-ignore
    let rs = await global.query(sql)
    //验证用户名和密码是否匹配
    if (rs.length === 0) {
        global.response(ctx, {
            "status": 200,
            "code": 500,
            "data": {},
            "msg": '用户不存在或用户名密码错误'
        })
        addLoginLog(ctx, false, post.username,'用户不存在或用户名密码错误')
        return
    }
    if (rs.length === 1) {
        const token = jwt.sign({
            data: post.username,
            exp: getTimestampAfterSeconds(global.config.loginMaxAge)
        }, global.config.secret)
        const user = rs[0]
        //部门信息
        const dept = await global.query(`select * from sys_dept where deptId = ${user.deptId}`)
        user.dept = dept[0]

        //权限集
        let permissions = []
        if(user.type == 1){ //高级管理员
            permissions.push("*:*:*")
        }

        //角色集
        let roles = []
        const roleSql = `SELECT * FROM sys_user_role INNER JOIN sys_role ON sys_user_role.roleId = sys_role.roleId WHERE sys_user_role.userId = ${user.userId}`
        const roleRs = await global.query(roleSql)
        for (let i in roleRs){
            roles.push(roleRs[i].roleName)
            if(user.type != 1){ //不是高级管理员
                const permissionSql = `SELECT perms FROM sys_role_menu INNER JOIN sys_menu ON sys_role_menu.menuId = sys_menu.menuId WHERE sys_role_menu.roleId = ${roleRs[i].roleId}`
                const permissionRs = await global.query(permissionSql)
                for (let j in permissionRs){
                    permissions.push(permissionRs[j].perms)
                }
            }
        }





        user.permissions = permissions
        user.roles = roles


        //redis
        if (global.config.redisOn) {
            await redis.connect()
            await redis.set(user.username, user)
            await redis.qiut()
        }

        //更新最后一次登陆情况
        sql = `update sys_user set 
                lastLoginTime=now() , 
                lastLoginIp = "${getUserIp(ctx.req)}",
                permissions = "${permissions}",
                roles = "${roles}",
                token = "${token}"
                where username='${post.username}'`
        // @ts-ignore
        rs = await global.query(sql)



        global.response(ctx, {
            "status": 200,
            "code": 200,
            "data": {
                permissions:permissions,
                roles:roles,
                user: user,
                token: token
            },
            "msg": '登陆成功'
        })
        addLoginLog(ctx, true, post.username,'登陆成功')

        return
    }
}
//添加日志表
function addLoginLog(ctx,status,username,msg){
    const sql = `INSERT INTO sys_log_login
                (username,ip,userAgent,status,msg) 
                VALUES
                ('${username}','${getUserIp(ctx.req)}','${ctx.request.headers["user-agent"]}','${status}','${msg}')`
    global.query(sql)
}
module.exports = login


